package com.example.mallcart.config;

import com.common.vo.MemberVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author guanglin.ma
 * @date 2024-01-06 10:55
 */
public class MgHandlerInterceptor implements HandlerInterceptor {

    // 本地线程对象  Map<thread,Object>
    public static ThreadLocal<MemberVO> threadLocal = new ThreadLocal();

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 通过HttpSession获取当前登录的用户信息
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute("login");
        if (attribute != null) {
            MemberVO memberVO = objectMapper.readValue((String) attribute, MemberVO.class);
            threadLocal.set(memberVO);
        }
        //都放过
        return true;
    }
}
